<?php
/**
 * @Author: liuhongbin
 * @Email: 514660094@qq.com
 * @Date: 2019-02-12 16:15:10
 * @Description:
 * @LastEditors: liuhongbin
 * @LastEditTime: xxx
 */

namespace app\controller\adminapi;

use app\common\model\platform\Platform;
use app\common\model\wework\WeworkApps;
use FormBuilder\Driver\CustomComponent;
use FormBuilder\Driver\FormComponent;
use hiduoke\services\CloudServer;
use think\App;
use think\facade\Cache;
use think\facade\Log;
use think\facade\Route;
use hiduoke\services\FormBuilder as Form;
use app\common\controller\AdminController;
use app\common\model\addon\Addons as AddonsModel;
use app\common\services\facade\Addons as AddonsServices;
use think\Request;
use think\swoole\response\File;

class Addons extends AdminController
{
    public $notLogin = ['icon'];
    public $notCheck = ['show'];
    /**
     * @var AddonsModel
     */
    public $model;

    public function __construct(App $app, AddonsModel $model)
    {
        parent::__construct($app);
        $this->model = $model;
    }


    /**
     * 获取应用列表
     * 可用应用、停用应用
     * @return \think\response\Json
     */
    public function index()
    {
        if (input('type', 0) == '0') {
            //已安装
            $res = $this->model->getPageList();
            $data = $res['data']->append(['type_name', 'new_version', 'auth', 'count_msg', 'used_platform_count', 'is_update']);
            return $this->success($res['count'], $data);
        } else {
            //未安装
            $installedAddons = $this->model->column('name');
            $addons = get_addon_list();
            $data = [];
            foreach ($addons as $key => $value) {
                if (in_array($value['name'], $installedAddons)) {
                    continue;
                }
                $data[] = array(
                    'author'    => $value['author'],
                    'name'      => $value['name'],
                    'title'     => $value['title'],
                    'status'    => $value['status'],
                    'version'   => $value['version'],
                    'type'      => $value['type'],
                    'app_type'  => $value['app_type'] ?? '',
                    'type_name' => $this->model->_types[$value['type']],
                    'icon'      => Route::buildUrl("/adminapi/addons/icon", ['name' => $value['name']])->domain(true)->build()
                );
            }
            return $this->success(count($data), $data);
        }
    }

    /**
     * 抓取未安装时候的图标
     */
    public function icon()
    {
        $name = input("name");
        $addon_path = $this->app->getRootPath() . "addons/" . $name . '/assets';
        $file_png = $addon_path . "/icon.png";
        if (file_exists($file_png)) {
            return new File($file_png);
        }
        $file_jpg = $addon_path . "/icon.jpg";
        if (file_exists($file_jpg)) {
            return new File($file_jpg);
        }
        $default = $this->app->getRootPath() . 'public/assets/img/common/logo.png';
        return new File($default);
    }

    /**
     * 应用详情
     */
    public function show()
    {
        $name = get_addon();
        $id = input("id", 0);
        if ($id) {
            $row = $this->model->where(['id' => $id])->append(['new_version', 'used_platform_count', 'visit', 'today_visit'])->find();
        } else {
            $row = $this->model->where(['name' => $name])->append(['new_version', 'used_platform_count', 'visit', 'today_visit'])->find();
        }
        if (!$row) {
            return $this->error("应用不存在");
        }
        if ($row['new_version'] && $row['new_version'] != $row['version']) {
            $row['is_update'] = true;
        } else {
            $row['is_update'] = false;
        }
        $row['info'] = get_addons_info($row['name']);
        $row['has_addon_config'] = $this->app->event->hasListener($row['name'] . '_addon_config');
        return $this->success("应用详情", $row);
    }

    /**
     * 编辑表单
     */
    public function form()
    {
        $id = input("id", 0);
        $rule = array();
        $form = Form::createForm("/adminapi/addons/setAddon")->setMethod("POST");
        $row = $this->model->where(['id' => $id])->findOrEmpty();
        $rule[] = Form::input('id', 'ID', $row->id)->disabled(true);
        $rule[] = Form::input('title', '应用名称', $row->title);
        $rule[] = Form::dkImage('icon', '图标', $row->icon);
        $rule[] = Form::textarea('description', '描述', $row->description)->rows('5');
        $form->setTitle("编辑")->setRule($rule);
        return $this->success("", Form::getFormData($form));
    }

    /**
     * 编辑应用
     */
    public function setAddon()
    {
        $data = input('formData');
        $id = intval($data['id']);
        $row = $this->model->where(['id' => $id])->findOrEmpty();
        if (!$row) {
            return $this->error("应用不存在");
        }
        $row->save($data);
        return $this->success("更新成功", $data);
    }

    /**
     * 禁用启用
     */
    public function status()
    {
        $id = input('id');
        $row = $this->model->where(['id' => $id])->find();
        if (!$row) {
            return $this->error("应用不存在");
        }
        $row->status = $row->status == 1 ? 0 : 1;
        $row->save();
        return $this->success("更新成功");
    }

    /**
     *安装
     * @return \think\response\Json
     */
    public function install()
    {
        $name = input("name");
        $count = $this->model->where(['name' => $name])->count();
        if ($count > 0) {
            return $this->error("当前应用已安装");
        }
        //插件安装
        $install_res = AddonsServices::install($name);
        if ($install_res !== true) {
            return $this->error($install_res);
        }
//        写入数据
        $addon = get_addons_info($name);
        $data = array(
            'name'        => $addon['name'],
            'title'       => $addon['title'],
            'description' => $addon['description'],
            'author'      => $addon['author'],
            'type'        => $addon['type'],
            'status'      => 1,
            'version'     => $addon['version'],
            'app_type'    => $addon['app_type'] ?? ''
        );
        $this->model->save($data);
        (new CloudServer())->updateSiteAddonVersion($addon['name'], $addon['version']);
        Cache::clear();
        return $this->success('安装成功', ['data' => $data, 'id' => $this->model->id]);
    }

    /**
     * 卸载
     */
    public function uninstall()
    {
        $name = input('name');
        //查询应用信息
        $addon = $this->model->where(['name' => $name])->find();
        if (!$addon) {
            return $this->error("当前应用不存在");
        }
        //执行卸载
        AddonsServices::uninstall($name);
        //删除对应数据
        $this->model->where(['name' => $name])->delete();
        (new CloudServer())->updateUninstallTime($name);
        return $this->success("卸载成功");
    }

    /**
     * 检查应用更新
     */
    public function checkUpgrade()
    {
        Cache::delete("new_versions");
        Cache::delete('getSiteAddonTokenCount');
        return $this->success('刷新成功');
    }

    /**
     * 更新应用
     */
    public function upgrade()
    {
        $name = input("name");
        $addon = $this->model->where(['name' => $name])->find();
        if (!$addon) {
            return $this->error('应用不存在');
        }
        //插件更新
        $install_res = AddonsServices::upgrade($name);
        if ($install_res !== true) {
            return $this->error($install_res);
        }
        //写入数据
        $info = get_addons_info($name);
        $data = array(
            'author'  => $info['author'],
            'version' => $info['version'],
        );
        $addon->save($data);
        (new CloudServer())->updateSiteAddonVersion($addon['name'], $info['version']);
        Cache::clear();
        return $this->success('更新成功', ['data' => $addon]);
    }
    //TODO 未实现


    /**
     * 本地上传应用
     */
    public function local()
    {

    }

    /**
     * 应用配置
     * @param $id
     * @return \think\response\Json
     */
    public function getAddonConfigForm($id)
    {
        $id = input("id", 0);
        $rule = array();
        $form = Form::createForm("/adminapi/addons/setAddonConfig")->setMethod("POST");
        $row = $this->model->where(['id' => $id])->findOrEmpty();
        $rule[] = Form::hidden('id', $row->id);
        $addon_rules = event($row['name'] . '_addon_config', $row['config'])[0] ?? [];
        if (is_array($addon_rules)) {
            foreach ($addon_rules as $key => $value) {
                if ($value instanceof FormComponent) {
                    $rule[] = $value;
                } elseif ($value instanceof CustomComponent) {
                    $rule[] = (new CustomComponent('elCol'))->appendChild($value)->props(['style' => 'margin-bottom:22px']);
                }
            }
        }
        $form->setTitle("应用配置")->setRule($rule);
        return $this->success("", Form::getFormData($form));
    }

    /***
     * 设置应用配置
     * @return \think\response\Json
     */
    public function setAddonConfig()
    {
        $data = input('formData');
        $id = intval($data['id']);
        $row = $this->model->where(['id' => $id])->findOrEmpty();
        if (!$row) {
            return $this->error("应用不存在");
        }
        unset($data['id']);
        $row->config = $data;
        $row->save();
        return $this->success("更新成功", $data);
    }
}
